import { SearchResult } from '@/types/data'
import { HistoryAction } from '@/types/store'
import { getHistory, setHistory } from '@/utils/storage'

type historyType = {
  suggestion: string[]
  histories: string[]
  searchResult: SearchResult
}
const initValue: historyType = {
  suggestion: [],
  histories: getHistory(),
  searchResult: {} as SearchResult,
}
export default function history(state = initValue, action: HistoryAction) {
  if (action.type === 'history/saveSuggestion') {
    return {
      ...state,
      suggestion: action.payload,
    }
  }
  if (action.type === 'history/clearSuggestion') {
    return {
      ...state,
      suggestion: [],
    }
  }
  if (action.type === 'history/saveHistory') {
    // 存储到本地
    setHistory(action.payload)
    return {
      ...state,
      histories: action.payload,
    }
  }
  if (action.type === 'history/saveSearchResult') {
    const old = state.searchResult.results || []
    return {
      ...state,
      searchResult: {
        ...state.searchResult,
        results: [...old, ...action.payload.results],
      },
    }
  }
  return state
}
